package com.yalu.service.data.impl;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.yalu.common.Constant;
import com.yalu.dao.data.SalesReportDao;
import com.yalu.service.data.SalesReportService;
import com.yalu.util.ReportExportUtil;
import com.yalu.util.ReportHeaderUtil;

import core.report.yearReport.bean.BaseExcelReportDataBean;
import core.report.yearReport.bean.ComparedSalesReportDataBean;
import core.report.yearReport.bean.CustomSalesReportDataBean;
import core.report.yearReport.bean.MergedBean;
import core.report.yearReport.bean.SalesReportDataBean;
import core.report.yearReport.bean.YearOrMonthOrWeekSalesReportDataBean;
import core.report.yearReport.util.ExportExcelUtil;

@Service
public class SalesReportServiceImpl implements SalesReportService {

	@Resource
	private SalesReportDao salesReportDao;

	@Override
	public void createReport(String dateType, String beginTime, String endTime,
			String resultFileName, String compareYear) {
		if (dateType.equals(Constant.YEAR_STRING)
				|| dateType.equals(Constant.MONTH_STRING)
				|| dateType.equals(Constant.WEEK_STRING)) {
			this.createNotComparableReport(dateType, beginTime, endTime,
					resultFileName);
		} else {
			this.createComparableReport(dateType, beginTime, endTime,
					resultFileName, compareYear);
		}
	}

	private void createComparableReport(String dateType, String beginTime,
			String endTime, String resultFileName, String compareYear) {
		System.out.println("------------1");
		List<SalesReportDataBean> lastDataList = salesReportDao
				.getSalesReportDataBeanList(dateType, beginTime,
						endTime, dateType, compareYear);
		List<SalesReportDataBean> dataList = salesReportDao
				.getSalesReportDataBeanList(dateType, beginTime, endTime, null,
						null);
		System.out.println("------------2");

		List<BaseExcelReportDataBean> lastExcelDataList = returnExcelDataList(
				dateType, lastDataList);
		List<BaseExcelReportDataBean> excelDataList = returnExcelDataList(
				dateType, dataList);
		List<ComparedSalesReportDataBean> subCompareExcelDataList = new ArrayList<ComparedSalesReportDataBean>();
		List<ComparedSalesReportDataBean> compareExcelDataList = new ArrayList<ComparedSalesReportDataBean>();
		for (BaseExcelReportDataBean tmp : excelDataList) {
			SalesReportDataBean data = (SalesReportDataBean) tmp;
			ComparedSalesReportDataBean compareData = ComparedSalesReportDataBean
					.createSalesReportDataBeanByDateType(dateType);
			compareData.setReportDataBean(data);
			compareData.setLastReportDataBean(SalesReportDataBean
					.createSalesReportDataBeanByDateType(dateType));
			if (data.getShopId() == 0) {// 不是商店 说明是平台小计或者总计
				compareData.setAttributeFlag(true);
			}
			subCompareExcelDataList.add(compareData);
		}
		compareExcelDataList.addAll(subCompareExcelDataList);
		for (BaseExcelReportDataBean lastTmp : lastExcelDataList) {

			SalesReportDataBean lastData = (SalesReportDataBean) lastTmp;
			boolean catchFlag = false;
			for (BaseExcelReportDataBean compareBean : subCompareExcelDataList) {
				ComparedSalesReportDataBean compareData = (ComparedSalesReportDataBean) compareBean;
				if (compareData.getReportDataBean().getShopId() == lastData
						.getShopId()
						&& compareData.getReportDataBean().getAttribute_id() == lastData
								.getAttribute_id()) {
					if (lastData.getShopId() == 0) {// 不是商店 说明是平台小计或者总计
						compareData.setAttributeFlag(true);
					}
					compareData.setLastReportDataBean(lastData);
					catchFlag = true;
					continue;
				}
			}
			if (!catchFlag) {
				ComparedSalesReportDataBean compareData = ComparedSalesReportDataBean
						.createSalesReportDataBeanByDateType(dateType);
				compareData.setReportDataBean(SalesReportDataBean
						.createSalesReportDataBeanByDateType(dateType));
				if (lastData.getShopId() == 0) {// 不是商店 说明是平台小计或者总计
					compareData.setAttributeFlag(true);
				}
				compareData.setLastReportDataBean(lastData);
				compareExcelDataList.add(compareData);
			}
		}

		System.out.println("------------3");
		Collections.sort(compareExcelDataList);// 排序

		// 垂直统计平均增长率
		calculateGrouthRate(compareExcelDataList);

		List<BaseExcelReportDataBean> exDataList = new ArrayList<BaseExcelReportDataBean>();
		exDataList.addAll(compareExcelDataList);
		
		List<MergedBean> headers = ReportHeaderUtil.getHeaders(dateType,
				beginTime, endTime, compareYear);
		ExportExcelUtil ex = new ExportExcelUtil();
		OutputStream out;
		try {
			File file = new File(resultFileName);
			out = new FileOutputStream(file);
			ex.exportExcel(ReportHeaderUtil.getSheetNameByDateType(dateType),
					headers, exDataList, out, ReportExportUtil
							.getBeginRowIndexByDateType(dateType),
					ReportHeaderUtil.getColCountByDateType(dateType), null);
			System.out.println("------------4");
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
	}

	private List<BaseExcelReportDataBean> returnExcelDataList(String dateType,
			List<SalesReportDataBean> dataList) {
		List<BaseExcelReportDataBean> excelDataList = new ArrayList<BaseExcelReportDataBean>();
		SalesReportDataBean propertiesBean = SalesReportDataBean
				.createSalesReportDataBeanByDateType(dateType);// 平台总计
		propertiesBean.setAttributeFlag(true);
		SalesReportDataBean totalBean = SalesReportDataBean
				.createSalesReportDataBeanByDateType(dateType);// 全部店铺总计
		totalBean.setAttributeFlag(true);
		totalBean.setName("合计");
		SalesReportDataBean lastData = null;
		int addCount = 0;
		for (int index = 0; index < dataList.size(); index++) {
			SalesReportDataBean data = dataList.get(index);
			totalBean.addProperties(data);
			if (lastData == null) {
				propertiesBean.setAttribute_id(data.getAttribute_id());
				propertiesBean.setName(ReportExportUtil
						.getAttributeNameById(data.getAttribute_id()));
				propertiesBean.addProperties(data);
				excelDataList.add(data);
			} else {
				if (lastData.getAttribute_id() == data.getAttribute_id()) {
					propertiesBean.addProperties(data);
					excelDataList.add(data);
				} else {
					propertiesBean.subtract(addCount);
					excelDataList.add(propertiesBean);
					addCount = 0;
					excelDataList.add(data);
					propertiesBean = SalesReportDataBean
							.createSalesReportDataBeanByDateType(dateType);
					propertiesBean.setAttributeFlag(true);
					propertiesBean.setAttribute_id(data.getAttribute_id());
					propertiesBean.setName(ReportExportUtil
							.getAttributeNameById(data.getAttribute_id()));
					propertiesBean.addProperties(data);
				}
			}
			if (index == dataList.size() - 1) {
				excelDataList.add(propertiesBean);
			}
			lastData = data;
			addCount++;
		}
		if (dataList.size() != 0) {
			totalBean.subtract(dataList.size());
			excelDataList.add(totalBean);
		}
		return excelDataList;
	}

	/**
	 * @Description: 无对比的报表
	 * @param dateType
	 * @param chooseTime
	 * @param resultFileName
	 * @date 2013-11-1 下午11:55:07
	 * @author zch
	 */
	private void createNotComparableReport(String dateType, String beginTime,
			String endTime, String resultFileName) {
		// chooseTime = chooseTime.replace("/", "");
		// String beginTime =
		// ReportExportUtil.getBeginTime(chooseTime,dateType);
		// String endTime = ReportExportUtil.getEndTime(chooseTime,dateType);
		System.out.println("------------1");
		List<SalesReportDataBean> dataList = salesReportDao
				.getSalesReportDataBeanList(dateType, beginTime, endTime, null,
						null);
		System.out.println("------------2");
		// 平台总计
		List<BaseExcelReportDataBean> excelDataList = returnExcelDataList(
				dateType, dataList);
		System.out.println("------------3");
		List<MergedBean> headers = ReportHeaderUtil.getHeaders(dateType,
				beginTime, endTime, null);
		ExportExcelUtil ex = new ExportExcelUtil();
		OutputStream out;
		try {
			File file = new File(resultFileName);
			out = new FileOutputStream(file);
			ex.exportExcel(ReportHeaderUtil.getSheetNameByDateType(dateType),
					headers, excelDataList, out, ReportExportUtil
							.getBeginRowIndexByDateType(dateType),
					ReportHeaderUtil.getColCountByDateType(dateType), null);
			System.out.println("------------4");
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
	}
	
	
	private void calculateGrouthRate(
			List<ComparedSalesReportDataBean> compareExcelDataList) {
		int allShopCount = 0;
		double grouthRate_totalAmount_all = 0;
		double grouthRate_cost_Amount_all = 0;
		double grouthRate_cost_accomplish_all = 0;
		double grouthRate_views_all = 0;
		double grouthRate_guests_all = 0;
		double grouthRate_success_rate_all = 0;
		double grouthRate_piecesPrice_all = 0;
		double grouthRate_pieces_per_price_all = 0;
		for (ComparedSalesReportDataBean shop : compareExcelDataList) {
			double grouthRate_totalAmount = 0;
			double grouthRate_cost_Amount = 0;
			double grouthRate_cost_accomplish = 0;
			double grouthRate_views = 0;
			double grouthRate_guests = 0;
			double grouthRate_success_rate = 0;
			double grouthRate_piecesPrice = 0;
			double grouthRate_pieces_per_price = 0;
			SalesReportDataBean data = shop.getReportDataBean();
			SalesReportDataBean lastData = shop.getLastReportDataBean();
			if (data.getShopId() != 0 || lastData.getShopId() != 0) {
				allShopCount++;
				grouthRate_totalAmount = (lastData.getTotalAmount()) != 0 ? ((data
						.getTotalAmount() - lastData.getTotalAmount()) / lastData
						.getTotalAmount())
						: 0;
				grouthRate_cost_Amount = (lastData.getCost_Amount()) != 0 ? ((data
						.getCost_Amount() - lastData.getCost_Amount()) / lastData
						.getCost_Amount())
						: 0;
				grouthRate_views = (lastData.getViews()) != 0 ? (((double) data
						.getViews() - (double) lastData.getViews()) / lastData
						.getViews()) : 0;
				grouthRate_guests = (lastData.getGuests()) != 0 ? ((data
						.getGuests() - lastData.getGuests()) / lastData
						.getGuests()) : 0;
				grouthRate_success_rate = (lastData.getSuccess_rate()) != 0 ? ((data
						.getSuccess_rate() - lastData.getSuccess_rate()) / lastData
						.getSuccess_rate())
						: 0;
				if (data instanceof YearOrMonthOrWeekSalesReportDataBean) {
					YearOrMonthOrWeekSalesReportDataBean tmpData = (YearOrMonthOrWeekSalesReportDataBean) data;
					YearOrMonthOrWeekSalesReportDataBean tmpLastData = (YearOrMonthOrWeekSalesReportDataBean) lastData;
					grouthRate_cost_accomplish = (tmpLastData.getCost_accomplish()) != 0 ? ((tmpData
							.getCost_accomplish() - tmpLastData
							.getCost_accomplish()) / tmpLastData
							.getCost_accomplish())
							: 0;
					grouthRate_piecesPrice = (tmpLastData.getPiecesPrice()) != 0 ? ((tmpData
							.getPiecesPrice() - tmpLastData.getPiecesPrice()) / tmpLastData
							.getPiecesPrice())
							: 0;
					grouthRate_pieces_per_price = (tmpLastData.getPieces_per_price()) != 0 ? ((tmpData
							.getPieces_per_price() - tmpLastData
							.getPieces_per_price()) / tmpLastData
							.getPieces_per_price())
							: 0;
				} else if (data instanceof CustomSalesReportDataBean) {
					CustomSalesReportDataBean tmpData = (CustomSalesReportDataBean) data;
					CustomSalesReportDataBean tmpLastData = (CustomSalesReportDataBean) lastData;
					grouthRate_piecesPrice = (tmpLastData.getPiecesPrice()) != 0 ? ((tmpData
							.getPiecesPrice() - tmpLastData.getPiecesPrice()) / tmpLastData
							.getPiecesPrice())
							: 0;
					grouthRate_pieces_per_price = (tmpLastData.getPieces_per_price()) != 0 ? ((tmpData
							.getPieces_per_price() - tmpLastData
							.getPieces_per_price()) / tmpLastData
							.getPieces_per_price())
							: 0;
				}
				shop.setGrouthRate_totalAmount(grouthRate_totalAmount);
				shop.setGrouthRate_cost_Amount(grouthRate_cost_Amount);
				shop.setGrouthRate_cost_accomplish(grouthRate_cost_accomplish);
				shop.setGrouthRate_views(grouthRate_views);
				shop.setGrouthRate_guests(grouthRate_guests);
				shop.setGrouthRate_success_rate(grouthRate_success_rate);
				shop.setGrouthRate_piecesPrice(grouthRate_piecesPrice);
				shop
						.setGrouthRate_pieces_per_price(grouthRate_pieces_per_price);
				continue;
			}
		}
		
		for (ComparedSalesReportDataBean propertie : compareExcelDataList) {
			double grouthRate_totalAmount = 0;
			double grouthRate_cost_Amount = 0;
			double grouthRate_cost_accomplish = 0;
			double grouthRate_views = 0;
			double grouthRate_guests = 0;
			double grouthRate_success_rate = 0;
			double grouthRate_piecesPrice = 0;
			double grouthRate_pieces_per_price = 0;
			SalesReportDataBean propertiedata = propertie.getReportDataBean();
			SalesReportDataBean lastpropertieData = propertie
					.getLastReportDataBean();
			if (propertiedata.getShopId() != 0
					|| lastpropertieData.getShopId() != 0) {
				continue;
			}
			int shopCount = 0;
			int propertieAttributeId = propertiedata.getAttribute_id() != 0 ? propertiedata
					.getAttribute_id()
					: lastpropertieData.getAttribute_id();
			for (ComparedSalesReportDataBean shop : compareExcelDataList) {
				SalesReportDataBean data = shop.getReportDataBean();
				SalesReportDataBean lastData = shop.getLastReportDataBean();
				if (data.getShopId() != 0 || lastData.getShopId() != 0) {
					int shopAttributeId = data.getAttribute_id() != 0 ? data
							.getAttribute_id() : lastData.getAttribute_id();
					if (shopAttributeId == 0
							|| propertieAttributeId != shopAttributeId) {
						continue;
					}
					shopCount++;
					grouthRate_totalAmount += shop.getGrouthRate_totalAmount();
					grouthRate_cost_Amount += shop.getGrouthRate_cost_Amount();
					grouthRate_cost_accomplish += shop
							.getGrouthRate_cost_accomplish();
					grouthRate_views += shop.getGrouthRate_views();
					grouthRate_guests += shop.getGrouthRate_guests();
					grouthRate_success_rate += shop
							.getGrouthRate_success_rate();
					grouthRate_piecesPrice += shop
							.getGrouthRate_pieces_per_price();
					grouthRate_pieces_per_price += shop
							.getGrouthRate_piecesPrice();
				}
			}
			propertie.setGrouthRate_totalAmount(grouthRate_totalAmount
					/ shopCount);
			propertie.setGrouthRate_cost_Amount(grouthRate_cost_Amount
					/ shopCount);
			propertie.setGrouthRate_cost_accomplish(grouthRate_cost_accomplish
					/ shopCount);
			propertie.setGrouthRate_views(grouthRate_views / shopCount);
			propertie.setGrouthRate_guests(grouthRate_guests / shopCount);
			propertie.setGrouthRate_success_rate(grouthRate_success_rate
					/ shopCount);
			propertie.setGrouthRate_piecesPrice(grouthRate_piecesPrice
					/ shopCount);
			propertie
					.setGrouthRate_pieces_per_price(grouthRate_pieces_per_price
							/ shopCount);
			grouthRate_totalAmount_all += grouthRate_totalAmount;
			grouthRate_cost_Amount_all += grouthRate_cost_Amount;
			grouthRate_cost_accomplish_all += grouthRate_cost_accomplish;
			grouthRate_views_all += grouthRate_views;
			grouthRate_guests_all += grouthRate_guests;
			grouthRate_success_rate_all += grouthRate_success_rate;
			grouthRate_piecesPrice_all += grouthRate_piecesPrice;
			grouthRate_pieces_per_price_all +=grouthRate_pieces_per_price;
			shopCount = 0;
			if (propertiedata.getAttribute_id()== 0
					&& lastpropertieData.getAttribute_id()== 0) {
				propertie.setGrouthRate_totalAmount(grouthRate_totalAmount_all
						/ allShopCount);
				propertie.setGrouthRate_cost_Amount(grouthRate_cost_Amount_all
						/ allShopCount);
				propertie.setGrouthRate_cost_accomplish(grouthRate_cost_accomplish_all
						/ allShopCount);
				propertie.setGrouthRate_views(grouthRate_views_all / allShopCount);
				propertie.setGrouthRate_guests(grouthRate_guests_all / allShopCount);
				propertie.setGrouthRate_success_rate(grouthRate_success_rate_all
						/ allShopCount);
				propertie.setGrouthRate_piecesPrice(grouthRate_piecesPrice
						/ allShopCount);
				propertie
						.setGrouthRate_pieces_per_price(grouthRate_pieces_per_price_all
								/ allShopCount);
			}
		}

	}

}
